import formDataService from '../services/formDataService';
import visitMonthPlanModel from '../model/visitMonthPlanModel';
import dTalkApi from '../core/dTalkApi';
import consumerRecoderModel from '../model/consumerRecoderModel';
import storeRecoderModel from '../model/storeRecoderModel';
import excelExportModel from '../model/excelExportModel';
import excelExportModel2 from '../model/excelExportModel2';
import * as moment from 'moment';
import userCheckInModel from '../model/userCheckInModel';
import storeInfoModel from '../model/storeInfoModel';
import addExportModel from '../model/addExportModel';
import addService from '../services/addService';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import emplModel from '../model/empl2Model';

const schedule = require("node-schedule");

class ExportService{
    constructor(){}
 
    async add(){
        
        // let access_token=await dTalkApiUtil.getAccessToken();
        addService.getEmplFromDD().catch(error=>{
            console.log('getEmplFromDD_Error',error.message);
        }); 
        //定时添加每天的报表数据
        let j = await schedule.scheduleJob('00 05 00 * * *', function () {
            exportService.addExcelExportData().catch(error=>{
                console.log('addExcelExportData_Error',error.message);
            });
        });
        let m = await schedule.scheduleJob('00 02 00 * * *', function () {
            exportService.addData().catch(error=>{
                console.log('addData_Error',error.message);
            });
        });
        //同步钉钉的部门中人员的数据
        // 部门id: 44766074 error_json===> { errmsg: '您的服务器调用钉钉开放平台当前接口的所有请求都被暂时禁用了, 
        // apiPath(/user/list), 从 2018-11-27 17:00:12到 2018-11-27 17:00:12 请求总次数超过了 300 次, 
        // 处罚将在 2018-11-27 17:00:13 结束.',errcode: 90002 }
        // unhandledRejection undefined
        let j2 = await schedule.scheduleJob('00 10 22 * * *', function () {
            addService.getEmplFromDD().catch(error=>{
                console.log('getEmplFromDD_Error',error.message);
            });
        });

       
    }
  

    //添加每一天的报表数据
    async addExcelExportData(){
        let access_token=await dTalkApiUtil.getAccessToken();
        //let arr=await emplModel.distinct('UserId',{});
        let userList=await visitMonthPlanModel.distinct("userId",{'$and':[{userId:{$ne:null}},{userId:{$ne:''}},{user:{$ne:''}},{user:{$ne:null}}]});
        //let userList=await visitMonthPlanModel.distinct("userId",{'$and':[{userId:{$in:arr}},{userId:{$ne:null}},{userId:{$ne:''}},{user:{$ne:''}},{user:{$ne:null}}]});
        console.log(userList.length)
        let date2=moment().format('YYYY-MM-DD');
        let date=moment(date2).subtract(1,'days').format('YYYY-MM-DD')
        if (userList.length > 0) {
            for (let employeeindex = 0; employeeindex < userList.length; employeeindex++) {
                let it = userList[employeeindex];
                let name:any=''
                let data5=await visitMonthPlanModel.findOne({userId:it,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo = await dTalkApi.getUserDetail(it,access_token);
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name;
                    }
                }
                //客户计划拜访数量
                let plan_count = await visitMonthPlanModel.count({ userId: it, planDate: date, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                let consumerRate_:any = 0;
                let count_visit=0
                if(plan_count>0){
                     //客户实际拜访数量
                    let count_visited_consumer = await consumerRecoderModel.count({ userid: it, planDate: date, comment: 2 })
                    let count_visited_store = await storeRecoderModel.count({ userid: it, planDate: date })
                    count_visit = count_visited_consumer + count_visited_store;
                    consumerRate_ = count_visit / plan_count;
                }

                //签到率
                let plan_day_count = await visitMonthPlanModel.distinct("planDate", {planDate:date, userId: it ,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }]});
                let checkInRate_ = 0; //签到率
                let checkInCount:any[]=[];
                if (plan_day_count.length>0) {
                    checkInCount = await userCheckInModel.distinct("date_",{ date_: date, userId: it, isCheckInNineAm: true })  //实际签到天数
                    checkInRate_ = (checkInCount.length / plan_day_count.length);
                } 
                let user_data=await userCheckInModel.findOne({userId: it,date_:date})   //当天的签到时间
                let time2:any=''
                if(user_data){
                    let time_1=user_data.checkin_time
                    if(time_1){
                        time2=moment(time_1).format('HH:mm:ss')
                    }
                }
            
                //新客户
                //计划拜访的新客户数量
                let count_plan_new_consumer = await visitMonthPlanModel.count({ planDate: date, userId: it, plantype: '新拓展客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                let new_consumerRate_ = 0;
                let count_visited_new_consumer=0;
                if (count_plan_new_consumer>0) {
                    //实际已经拜访的新客户数量
                    count_visited_new_consumer= await consumerRecoderModel.count({ planDate: date, userid: it, planType: '新拓展客户', comment: 2 });
                    new_consumerRate_ = (count_visited_new_consumer / count_plan_new_consumer);
                }

                //出差频率
                //非BASE地签到天数
                let unBase_check = 0;
                let store_data = await storeRecoderModel.find({ userid: it, planDate: date, isChuchai: true });
                let con_data = await consumerRecoderModel.find({ userid: it, planDate: date, isChuchai: true, comment: 2 })
                if (store_data.length > 0 || con_data.length > 0) {
                    unBase_check = 1
                } else {
                    unBase_check = 0
                }

                //已拜访门店达标率与门店拜访进度
                //门店已经拜访的数量
                let plan_store = await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店' })
                let count_store=0;
                //已拜访门店拜访达标率
                let reachStoreRate:any = 0;
                if (plan_store>0) {
                     //门店已经拜访的数量中店铺达标的数量
                     count_store= await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店', isListStandard: true });
                    reachStoreRate = (count_store / plan_store);
                } 
                
                //门店拜访进度
                //员工名下的所有的客户
                let conList = await consumerRecoderModel.distinct("consumerCode", { userid: it, comment: 1 });
                //员工名下的所有的门店
                //let count_totalStore_oneEmployee = await storeInfoModel.collection.countDocuments({ consumerCode: { $in: conList } });
                let count_totalStore_oneEmployee = await storeInfoModel.distinct('storeCode',{ consumerCode: { $in: conList } });
                //门店拜访进度
                let shop_schedule:any = 0;
                if (count_totalStore_oneEmployee.length == 0) {
                    shop_schedule = 0;
                } else {
                    shop_schedule = (plan_store / count_totalStore_oneEmployee.length);
                }

                //=============================新增===========================================================
                //现有客户拜访达成率
                //现有客户的拜访计划的条数
                let count_plan_now_consumer = await visitMonthPlanModel.count({ planDate: date, userId: it, plantype: '现有客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                //现有客户拜访达成率
                let now_consumerRate_ = 0;
                let count_visited_now_consumer=0;//实际拜访的现有客户数量
                if (count_plan_now_consumer>0){
                     //实际拜访的现有客户数量
                    count_visited_now_consumer=await consumerRecoderModel.count({planDate: date, userid: it, planType: '现有客户', comment: 2})
                    now_consumerRate_ = (count_visited_now_consumer / count_plan_now_consumer);
                }
                //=============================新增===========================================================

                let ad=await excelExportModel.create({
                    userId:it,
                    userName:name,
                    date_:date,
                    visitCount_plan:plan_count,//计划拜访客户数量(一天)
                    actuall_visitCount:count_visit,//实际拜访数量
                    consumerRate:consumerRate_.toFixed(2), //客户拜访达成率(一天)

                    newConsumerRate:new_consumerRate_.toFixed(2), //新客户拜访达成率
                    newConsumerCount_plan:count_plan_new_consumer,//计划拜访新客户数量
                    newConsumerCount_visit:count_visited_new_consumer,//实际拜访新客户数量

                    checkInRate:checkInRate_.toFixed(2),//签到率
                    actuall_checkIn:checkInCount.length,//实际签到天数
                    checkInTime:time2,

                    unBase_check:unBase_check,

                    reachStandardRate:reachStoreRate.toFixed(2),//已拜访门店达标率
                    reachStandardStoreCount:count_store,//门店达标的数量

                    visitedStoreCount:plan_store,//已经拜访的门店数量

                    storeSchadule:shop_schedule.toFixed(2),//门店拜访进度
                    totalCountStore:count_totalStore_oneEmployee.length,//员工名下总的门店数量
                    //=============================新增==========================
                    nowConsumerRate:now_consumerRate_.toFixed(2),//现有客户拜访达成率
                    visitCount_plan_nowConsumer:count_plan_now_consumer,//现有客户计划拜访数量
                    nowConsumerCount_visit:count_visited_now_consumer,//实际拜访现有客户数量
                    //=============================新增==========================
                    
                    year: moment(date).format('YYYY'),
                    month:  moment(date).format('MM'),
                    comment:1
                })
                console.log(ad,'date_date_date_date_',date,it,employeeindex)
            }
        }  
    }


    
    //添加每一天的报表数据
    async addExcelExportData2(){
        let access_token=await dTalkApiUtil.getAccessToken();
        //let arr=await emplModel.distinct('UserId',{});
        let userList=await visitMonthPlanModel.distinct("userId",{'$and':[{userId:{$ne:null}},{userId:{$ne:''}},{user:{$ne:''}},{user:{$ne:null}}]});
        //let userList=await visitMonthPlanModel.distinct("userId",{'$and':[{userId:{$in:arr}},{userId:{$ne:null}},{userId:{$ne:''}},{user:{$ne:''}},{user:{$ne:null}}]});
        console.log(userList.length)
        let dateArr=['2019-03-02','2019-03-03','2019-03-04']   //需要导出数据的日期列表
        //let dateArr=['2019-02-25','2019-02-26','2019-02-27','2019-02-28']
        if(dateArr.length>0){
            for (let dateindex = 0; dateindex < dateArr.length; dateindex++) {
                let date3 = dateArr[dateindex];
                let date2=moment(date3).format('YYYY-MM-DD');
                let date=moment(date2).subtract(1,'days').format('YYYY-MM-DD')
                if (userList.length > 0) {
                    for (let employeeindex = 0; employeeindex < userList.length; employeeindex++) {
                        let it = userList[employeeindex];
                        let name:any=''
                        let data5=await emplModel.findOne({userId:it,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                        if(data5){
                            name=data5.userName
                        }else{
                            let employeeInfo = await dTalkApi.getUserDetail(it,access_token);
                            if (employeeInfo&&employeeInfo.name) {
                                name=employeeInfo.name;
                            }
                        }
                        //客户计划拜访数量
                        let plan_count = await visitMonthPlanModel.count({ userId: it, planDate: date, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                        let consumerRate_:any = 0;
                        let count_visit=0
                        if(plan_count>0){
                             //客户实际拜访数量
                            let count_visited_consumer = await consumerRecoderModel.count({ userid: it, planDate: date, comment: 2 })
                            let count_visited_store = await storeRecoderModel.count({ userid: it, planDate: date })
                            count_visit = count_visited_consumer + count_visited_store;
                            consumerRate_ = count_visit / plan_count;
                        }
        
                        //签到率
                        let plan_day_count = await visitMonthPlanModel.distinct("planDate", {planDate:date, userId: it ,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }]});
                        let checkInRate_ = 0; //签到率
                        let checkInCount:any[]=[];
                        if (plan_day_count.length>0) {
                            checkInCount = await userCheckInModel.distinct("date_",{ date_: date, userId: it, isCheckInNineAm: true })  //实际签到天数
                            checkInRate_ = (checkInCount.length / plan_day_count.length);
                        } 
                        let user_data=await userCheckInModel.findOne({userId: it,date_:date})   //当天的签到时间
                        let time2:any=''
                        if(user_data){
                            let time_1=user_data.checkin_time
                            if(time_1){
                                time2=moment(time_1).format('HH:mm:ss')
                            }
                        }
                    
                        //新客户
                        //计划拜访的新客户数量
                        let count_plan_new_consumer = await visitMonthPlanModel.count({ planDate: date, userId: it, plantype: '新拓展客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                        let new_consumerRate_ = 0;
                        let count_visited_new_consumer=0;
                        if (count_plan_new_consumer>0) {
                            //实际已经拜访的新客户数量
                            count_visited_new_consumer= await consumerRecoderModel.count({ planDate: date, userid: it, planType: '新拓展客户', comment: 2 });
                            new_consumerRate_ = (count_visited_new_consumer / count_plan_new_consumer);
                        }
        
                        //出差频率
                        //非BASE地签到天数
                        let unBase_check = 0;
                        let store_data = await storeRecoderModel.find({ userid: it, planDate: date, isChuchai: true });
                        let con_data = await consumerRecoderModel.find({ userid: it, planDate: date, isChuchai: true, comment: 2 })
                        if (store_data.length > 0 || con_data.length > 0) {
                            unBase_check = 1
                        } else {
                            unBase_check = 0
                        }
        
                        //已拜访门店达标率与门店拜访进度
                        //门店已经拜访的数量
                        let plan_store = await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店' })
                        let count_store=0;
                        //已拜访门店拜访达标率
                        let reachStoreRate:any = 0;
                        if (plan_store>0) {
                             //门店已经拜访的数量中店铺达标的数量
                             count_store= await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店', isListStandard: true });
                            reachStoreRate = (count_store / plan_store);
                        } 
                        
                        //门店拜访进度
                        //员工名下的所有的客户
                        let conList = await consumerRecoderModel.distinct("consumerCode", { userid: it, comment: 1 });
                        //员工名下的所有的门店
                        //let count_totalStore_oneEmployee = await storeInfoModel.collection.countDocuments({ consumerCode: { $in: conList } });
                        let count_totalStore_oneEmployee = await storeInfoModel.distinct('storeCode',{ consumerCode: { $in: conList } });
                        //门店拜访进度
                        let shop_schedule:any = 0;
                        if (count_totalStore_oneEmployee.length == 0) {
                            shop_schedule = 0;
                        } else {
                            shop_schedule = (plan_store / count_totalStore_oneEmployee.length);
                        }
        
                        //=============================新增===========================================================
                        //现有客户拜访达成率
                        //现有客户的拜访计划的条数
                        let count_plan_now_consumer = await visitMonthPlanModel.count({ planDate: date, userId: it, plantype: '现有客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                        //现有客户拜访达成率
                        let now_consumerRate_ = 0;
                        let count_visited_now_consumer=0;//实际拜访的现有客户数量
                        if (count_plan_now_consumer>0){
                             //实际拜访的现有客户数量
                            count_visited_now_consumer=await consumerRecoderModel.count({planDate: date, userid: it, planType: '现有客户', comment: 2})
                            now_consumerRate_ = (count_visited_now_consumer / count_plan_now_consumer);
                        }
                        //=============================新增===========================================================
                        let data9=await excelExportModel.findOne({userId:it,date_:date});
                        if(data9){
                            let ad=await excelExportModel.update({_id:data9._id},{
                                userId:it,
                                userName:name,
                                date_:date,
                                visitCount_plan:plan_count,//计划拜访客户数量(一天)
                                actuall_visitCount:count_visit,//实际拜访数量
                                consumerRate:consumerRate_.toFixed(2), //客户拜访达成率(一天)
            
                                newConsumerRate:new_consumerRate_.toFixed(2), //新客户拜访达成率
                                newConsumerCount_plan:count_plan_new_consumer,//计划拜访新客户数量
                                newConsumerCount_visit:count_visited_new_consumer,//实际拜访新客户数量
            
                                checkInRate:checkInRate_.toFixed(2),//签到率
                                actuall_checkIn:checkInCount.length,//实际签到天数
                                checkInTime:time2,
            
                                unBase_check:unBase_check,
            
                                reachStandardRate:reachStoreRate.toFixed(2),//已拜访门店达标率
                                reachStandardStoreCount:count_store,//门店达标的数量
            
                                visitedStoreCount:plan_store,//已经拜访的门店数量
            
                                storeSchadule:shop_schedule.toFixed(2),//门店拜访进度
                                totalCountStore:count_totalStore_oneEmployee.length,//员工名下总的门店数量
                                //=============================新增==========================
                                nowConsumerRate:now_consumerRate_.toFixed(2),//现有客户拜访达成率
                                visitCount_plan_nowConsumer:count_plan_now_consumer,//现有客户计划拜访数量
                                nowConsumerCount_visit:count_visited_now_consumer,//实际拜访现有客户数量
                                //=============================新增==========================
                                
                                year: moment(date).format('YYYY'),
                                month:  moment(date).format('MM'),
                                comment:1
                            })
                            console.log(ad,'date_date_date_date_',date,it,employeeindex,'=========update=========')
                        }else{
                            let ad=await excelExportModel.create({
                                userId:it,
                                userName:name,
                                date_:date,
                                visitCount_plan:plan_count,//计划拜访客户数量(一天)
                                actuall_visitCount:count_visit,//实际拜访数量
                                consumerRate:consumerRate_.toFixed(2), //客户拜访达成率(一天)
            
                                newConsumerRate:new_consumerRate_.toFixed(2), //新客户拜访达成率
                                newConsumerCount_plan:count_plan_new_consumer,//计划拜访新客户数量
                                newConsumerCount_visit:count_visited_new_consumer,//实际拜访新客户数量
            
                                checkInRate:checkInRate_.toFixed(2),//签到率
                                actuall_checkIn:checkInCount.length,//实际签到天数
                                checkInTime:time2,
            
                                unBase_check:unBase_check,
            
                                reachStandardRate:reachStoreRate.toFixed(2),//已拜访门店达标率
                                reachStandardStoreCount:count_store,//门店达标的数量
            
                                visitedStoreCount:plan_store,//已经拜访的门店数量
            
                                storeSchadule:shop_schedule.toFixed(2),//门店拜访进度
                                totalCountStore:count_totalStore_oneEmployee.length,//员工名下总的门店数量
                                //=============================新增==========================
                                nowConsumerRate:now_consumerRate_.toFixed(2),//现有客户拜访达成率
                                visitCount_plan_nowConsumer:count_plan_now_consumer,//现有客户计划拜访数量
                                nowConsumerCount_visit:count_visited_now_consumer,//实际拜访现有客户数量
                                //=============================新增==========================
                                
                                year: moment(date).format('YYYY'),
                                month:  moment(date).format('MM'),
                                comment:1
                            })
                            console.log(ad,'date_date_date_date_',date,it,employeeindex)
                        }
                       
                    }
                }  
            }
        }
    }
  
    //添加addExporModel数据-----日均
    async addData(){
        let access_token=await dTalkApiUtil.getAccessToken();
        let date2=moment().format('YYYY-MM-DD');
        let date=moment(date2).subtract(1,'days').format('YYYY-MM-DD')
        let year=moment(date).format('YYYY');
        // console.log(dateList,'dateList')
        let data7=await addExportModel.distinct('name_id',{})
        // console.log(data7,'<---------------------长度11111')
        let data3=await dTalkApi.getUserList('63824079',access_token)
        let list_3:any[]=[]
        if(data3&&data3.userlist&&data3.userlist.length>0){
            for (let index_3 = 0; index_3 < data3.userlist.length; index_3++) {
                let empl = data3.userlist[index_3];
                list_3.push(empl.userid) 
            }
        }
        // console.log(list_3,'????????????????') 
        let areaList:any =[]
        if(data7.length>0){
            for (let index = 0; index < data7.length; index++) {
                let element = data7[index];
                let data8=await addExportModel.findOne({name_id:element,"$and":[{name_:{$ne:null}},{name_:{$ne:''}}]});
                areaList.push({
                    id:element,
                    name:data8.name_
                })
            }
        }
        // console.log(areaList,'<---------------------长度11111',areaList.length)
        if(areaList.length==0){
            let list_1=await visitMonthPlanModel.distinct('nation',{'$and':[{nation:{$ne:null}},{nation:{$ne:''}}]})
            let nation:any=''
            if(list_1.length>0){
                list_1.map(it=>{
                    nation=it
                })
            }
            let a2=await visitMonthPlanModel.findOne({nation:nation,'$and':[{nationName:{$ne:null}},{nationName:{$ne:''}}]},{nationName:1,_id:0})
            let data=await dTalkApi.getSondepIdList(nation,false,access_token)
            let modelList=data.deptNames;   //模块
            let data2=await dTalkApi.getSondepIdList(nation,true,access_token)
            for (let index = 0; index < data2.dept.length; index++) {
                let element = data2.dept[index];
                if(modelList.includes(element.name)){
                    continue;
                }
                areaList.push(element)
            }
        }
        console.log(areaList,'<------------------1',areaList.length)
        if(areaList.length>0){
            for (let index_4 = 0; index_4 < areaList.length; index_4++) {
                let element = areaList[index_4];
                let id=element.id;
                let name=element.name
                let userList3:any[]=[]         
                if(id=='63824079'){
                    userList3=list_3
                }else{
                    userList3=await visitMonthPlanModel.distinct('userId',{'$or':[{areaName:name},{provinceName:name}],'$and':[{userId:{$ne:null}},{userId:{$ne:''}}]})
                }
                let consumerCount_day=0
                for (let b = 0; b < userList3.length; b++) {
                    let user_id = userList3[b];
                    let count =await formDataService.getCountConsumer_one_employeeDate1ToDate2(user_id,date,date)
                    consumerCount_day+=count;
                }
                let count3:any=0;
                if(userList3.length>0){
                  let count2:any=consumerCount_day/userList3.length;
                  count3=count2.toFixed(2)*1
                }
                let e=await addExportModel.create({
                    name_id:id,
                    name_:name,
                    date_:date,
                    month:moment(date).format('MM'),
                    consumerCount_day:consumerCount_day,//日均
                    consumerCount_empl:count3,//人均    默认全部是0
                    year:year,
                    comment:1
                })
                console.log(e,'e_e_e_e_e_e_',name,date,consumerCount_day,count3)
            }
        } 
    }

  

    

    async run(){
        // let year=2018;
        // let month=12;//4-12
        // let dateList:any[]=[];
        // for (let a = 0; a < 31; a++) {
        //     if(a<9){
        //         let date=year+'-'+month+'-0'+(a+1)
        //         dateList.push(date);
        //     }else{
        //         let date=year+'-'+month+'-'+(a+1)
        //         dateList.push(date);
        //     }
        // }
        // console.log(dateList,'日期列表')
        let access_token=await dTalkApiUtil.getAccessToken();
        let arr=await emplModel.distinct('UserId',{});
        //let userList=await visitMonthPlanModel.distinct("userId",{'$and':[{userId:{$ne:null}},{userId:{$ne:''}},{user:{$ne:''}},{user:{$ne:null}}]});
        let userList=await visitMonthPlanModel.distinct("userId",{'$and':[{userId:{$in:arr}},{userId:{$ne:null}},{userId:{$ne:''}},{user:{$ne:''}},{user:{$ne:null}}]});
        console.log(userList.length)
        /* 
        for (let dateindex = 0; dateindex < dateList.length; dateindex++) {
            let date = dateList[dateindex];
            if (userList.length > 0) {
                for (let employeeindex = 0; employeeindex < userList.length; employeeindex++) {
                    let it = userList[employeeindex];
                    let name:any=''
                    
                    let data5=await visitMonthPlanModel.findOne({userId:it,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                    if(data5){
                        name=data5.user
                    }else{
                        let employeeInfo = await dTalkApi.getUserDetail(it,access_token);
                        if (employeeInfo&&employeeInfo.name) {
                            name=employeeInfo.name;
                        }
                    }
                    //客户计划拜访数量
                    let plan_count = await visitMonthPlanModel.collection.countDocuments({ userId: it, planDate: date, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                    let consumerRate_:any = 0;
                    let count_visit=0
                    if(plan_count>0){
                         //客户实际拜访数量
                        let count_visited_consumer = await consumerRecoderModel.collection.countDocuments({ userid: it, planDate: date, comment: 2 })
                        let count_visited_store = await storeRecoderModel.collection.countDocuments({ userid: it, planDate: date })
                        count_visit = count_visited_consumer + count_visited_store;
                        consumerRate_ = count_visit / plan_count;
                    }
    
                    //签到率
                    let plan_day_count = await visitMonthPlanModel.distinct("planDate", {planDate:date, userId: it ,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }]});
                    let checkInRate_ = 0; //签到率
                    let checkInCount:any[]=[];
                    if (plan_day_count.length>0) {
                        checkInCount = await userCheckInModel.distinct("date_",{ date_: date, userId: it, isCheckInNineAm: true })  //实际签到天数
                        checkInRate_ = (checkInCount.length / plan_day_count.length);
                    } 
                    let user_data=await userCheckInModel.findOne({userId: it,date_:date})   //当天的签到时间
                    let time2:any=''
                    if(user_data){
                        let time_1=user_data.checkin_time
                        if(time_1){
                            time2=moment(time_1).format('HH:mm:ss')
                        }
                    }
                
                    //新客户
                    //计划拜访的新客户数量
                    let count_plan_new_consumer = await visitMonthPlanModel.collection.countDocuments({ planDate: date, userId: it, plantype: '新拓展客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                    let new_consumerRate_ = 0;
                    let count_visited_new_consumer=0;
                    if (count_plan_new_consumer>0) {
                        //实际已经拜访的新客户数量
                        count_visited_new_consumer= await consumerRecoderModel.collection.countDocuments({ planDate: date, userid: it, planType: '新拓展客户', comment: 2 });
                        new_consumerRate_ = (count_visited_new_consumer / count_plan_new_consumer);
                    }
    
                    //出差频率
                    //非BASE地签到天数
                    let unBase_check = 0;
                    let store_data = await storeRecoderModel.find({ userid: it, planDate: date, isChuchai: true });
                    let con_data = await consumerRecoderModel.find({ userid: it, planDate: date, isChuchai: true, comment: 2 })
                    if (store_data.length > 0 || con_data.length > 0) {
                        unBase_check = 1
                    } else {
                        unBase_check = 0
                    }
    
                    //已拜访门店达标率与门店拜访进度
                    //门店已经拜访的数量
                    let plan_store = await storeRecoderModel.collection.countDocuments({ userid: it, planDate: date, planType: '门店' })
                    let count_store=0;
                    //已拜访门店拜访达标率
                    let reachStoreRate:any = 0;
                    if (plan_store>0) {
                         //门店已经拜访的数量中店铺达标的数量
                         count_store= await storeRecoderModel.collection.countDocuments({ userid: it, planDate: date, planType: '门店', isListStandard: true });
                        reachStoreRate = (count_store / plan_store);
                    } 
                    
                    //门店拜访进度
                    //员工名下的所有的客户
                    let conList = await consumerRecoderModel.distinct("consumerCode", { userid: it, comment: 1 });
                    //员工名下的所有的门店
                    let count_totalStore_oneEmployee = await storeInfoModel.collection.countDocuments({ consumerCode: { $in: conList } });
                    //门店拜访进度
                    let shop_schedule:any = 0;
                    if (count_totalStore_oneEmployee == 0) {
                        shop_schedule = 0;
                    } else {
                        shop_schedule = (plan_store / count_totalStore_oneEmployee);
                    }
    
                    //=============================新增===========================================================
                    //现有客户拜访达成率
                    //现有客户的拜访计划的条数
                    let count_plan_now_consumer = await visitMonthPlanModel.collection.countDocuments({ planDate: date, userId: it, plantype: '现有客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                    //现有客户拜访达成率
                    let now_consumerRate_ = 0;
                    let count_visited_now_consumer=0;//实际拜访的现有客户数量
                    if (count_plan_now_consumer>0){
                         //实际拜访的现有客户数量
                        count_visited_now_consumer=await consumerRecoderModel.collection.countDocuments({planDate: date, userid: it, planType: '现有客户', comment: 2})
                        now_consumerRate_ = (count_visited_now_consumer / count_plan_now_consumer);
                    }
                    //=============================新增===========================================================
    
                    let ad=await excelExportModel2.create({
                        userId:it,
                        userName:name,
                        date_:date,
                        visitCount_plan:plan_count,//计划拜访客户数量(一天)
                        actuall_visitCount:count_visit,//实际拜访数量
                        consumerRate:consumerRate_.toFixed(2), //客户拜访达成率(一天)
    
                        newConsumerRate:new_consumerRate_.toFixed(2), //新客户拜访达成率
                        newConsumerCount_plan:count_plan_new_consumer,//计划拜访新客户数量
                        newConsumerCount_visit:count_visited_new_consumer,//实际拜访新客户数量
    
                        checkInRate:checkInRate_.toFixed(2),//签到率
                        actuall_checkIn:checkInCount.length,//实际签到天数
                        checkInTime:time2,
    
                        unBase_check:unBase_check,
    
                        reachStandardRate:reachStoreRate.toFixed(2),//已拜访门店达标率
                        reachStandardStoreCount:count_store,//门店达标的数量
    
                        visitedStoreCount:plan_store,//已经拜访的门店数量
    
                        storeSchadule:shop_schedule.toFixed(2),//门店拜访进度
                        totalCountStore:count_totalStore_oneEmployee,//员工名下总的门店数量
                        //=============================新增==========================
                        nowConsumerRate:now_consumerRate_.toFixed(2),//现有客户拜访达成率
                        visitCount_plan_nowConsumer:count_plan_now_consumer,//现有客户计划拜访数量
                        nowConsumerCount_visit:count_visited_now_consumer,//实际拜访现有客户数量
                        //=============================新增==========================
                        
                        year: moment(date).format('YYYY'),
                        month:  moment(date).format('MM'),
                        comment:1
                    })
                    console.log(ad._id,'date_date_date_date_',date,it,'userId_,name>>',name,employeeindex)
                }
            } 
        } */
        let date='2019-01-03';
        if (userList.length > 0) {
            for (let employeeindex = 0; employeeindex < userList.length; employeeindex++) {
                let it = userList[employeeindex];
                let name:any=''
                
                let data5=await visitMonthPlanModel.findOne({userId:it,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                if(data5){
                    name=data5.user
                }else{
                    let employeeInfo = await dTalkApi.getUserDetail(it,access_token);
                    if (employeeInfo&&employeeInfo.name) {
                        name=employeeInfo.name;
                    }
                }
                //客户计划拜访数量
                let plan_count = await visitMonthPlanModel.count({ userId: it, planDate: date, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                let consumerRate_:any = 0;
                let count_visit=0
                if(plan_count>0){
                     //客户实际拜访数量
                    let count_visited_consumer = await consumerRecoderModel.count({ userid: it, planDate: date, comment: 2 })
                    let count_visited_store = await storeRecoderModel.count({ userid: it, planDate: date })
                    count_visit = count_visited_consumer + count_visited_store;
                    consumerRate_ = count_visit / plan_count;
                }

                //签到率
                let plan_day_count = await visitMonthPlanModel.distinct("planDate", {planDate:date, userId: it ,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }]});
                let checkInRate_ = 0; //签到率
                let checkInCount:any[]=[];
                if (plan_day_count.length>0) {
                    checkInCount = await userCheckInModel.distinct("date_",{ date_: date, userId: it, isCheckInNineAm: true })  //实际签到天数
                    checkInRate_ = (checkInCount.length / plan_day_count.length);
                } 
                let user_data=await userCheckInModel.findOne({userId: it,date_:date})   //当天的签到时间
                let time2:any=''
                if(user_data){
                    let time_1=user_data.checkin_time
                    if(time_1){
                        time2=moment(time_1).format('HH:mm:ss')
                    }
                }
            
                //新客户
                //计划拜访的新客户数量
                let count_plan_new_consumer = await visitMonthPlanModel.count({ planDate: date, userId: it, plantype: '新拓展客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                let new_consumerRate_ = 0;
                let count_visited_new_consumer=0;
                if (count_plan_new_consumer>0) {
                    //实际已经拜访的新客户数量
                    count_visited_new_consumer= await consumerRecoderModel.count({ planDate: date, userid: it, planType: '新拓展客户', comment: 2 });
                    new_consumerRate_ = (count_visited_new_consumer / count_plan_new_consumer);
                }

                //出差频率
                //非BASE地签到天数
                let unBase_check = 0;
                let store_data = await storeRecoderModel.find({ userid: it, planDate: date, isChuchai: true });
                let con_data = await consumerRecoderModel.find({ userid: it, planDate: date, isChuchai: true, comment: 2 })
                if (store_data.length > 0 || con_data.length > 0) {
                    unBase_check = 1
                } else {
                    unBase_check = 0
                }

                //已拜访门店达标率与门店拜访进度
                //门店已经拜访的数量
                let plan_store = await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店' })
                let count_store=0;
                //已拜访门店拜访达标率
                let reachStoreRate:any = 0;
                if (plan_store>0) {
                     //门店已经拜访的数量中店铺达标的数量
                     count_store= await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店', isListStandard: true });
                    reachStoreRate = (count_store / plan_store);
                } 
                
                //门店拜访进度
                //员工名下的所有的客户
                let conList = await consumerRecoderModel.distinct("consumerCode", { userid: it, comment: 1 });
                //员工名下的所有的门店
                //let count_totalStore_oneEmployee = await storeInfoModel.collection.countDocuments({ consumerCode: { $in: conList } });
                let count_totalStore_oneEmployee = await storeInfoModel.distinct('storeCode',{ consumerCode: { $in: conList } });
                //门店拜访进度
                let shop_schedule:any = 0;
                if (count_totalStore_oneEmployee.length == 0) {
                    shop_schedule = 0;
                } else {
                    shop_schedule = (plan_store / count_totalStore_oneEmployee.length);
                }

                //=============================新增===========================================================
                //现有客户拜访达成率
                //现有客户的拜访计划的条数
                let count_plan_now_consumer = await visitMonthPlanModel.count({ planDate: date, userId: it, plantype: '现有客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                //现有客户拜访达成率
                let now_consumerRate_ = 0;
                let count_visited_now_consumer=0;//实际拜访的现有客户数量
                if (count_plan_now_consumer>0){
                     //实际拜访的现有客户数量
                    count_visited_now_consumer=await consumerRecoderModel.count({planDate: date, userid: it, planType: '现有客户', comment: 2})
                    now_consumerRate_ = (count_visited_now_consumer / count_plan_now_consumer);
                }
                //=============================新增===========================================================

                let ad=await excelExportModel2.create({
                    userId:it,
                    userName:name,
                    date_:date,
                    visitCount_plan:plan_count,//计划拜访客户数量(一天)
                    actuall_visitCount:count_visit,//实际拜访数量
                    consumerRate:consumerRate_.toFixed(2), //客户拜访达成率(一天)

                    newConsumerRate:new_consumerRate_.toFixed(2), //新客户拜访达成率
                    newConsumerCount_plan:count_plan_new_consumer,//计划拜访新客户数量
                    newConsumerCount_visit:count_visited_new_consumer,//实际拜访新客户数量

                    checkInRate:checkInRate_.toFixed(2),//签到率
                    actuall_checkIn:checkInCount.length,//实际签到天数
                    checkInTime:time2,

                    unBase_check:unBase_check,

                    reachStandardRate:reachStoreRate.toFixed(2),//已拜访门店达标率
                    reachStandardStoreCount:count_store,//门店达标的数量

                    visitedStoreCount:plan_store,//已经拜访的门店数量

                    storeSchadule:shop_schedule.toFixed(2),//门店拜访进度
                    totalCountStore:count_totalStore_oneEmployee.length,//员工名下总的门店数量
                    //=============================新增==========================
                    nowConsumerRate:now_consumerRate_.toFixed(2),//现有客户拜访达成率
                    visitCount_plan_nowConsumer:count_plan_now_consumer,//现有客户计划拜访数量
                    nowConsumerCount_visit:count_visited_now_consumer,//实际拜访现有客户数量
                    //=============================新增==========================
                    
                    year: moment(date).format('YYYY'),
                    month:  moment(date).format('MM'),
                    comment:1
                })
                console.log(ad._id,'date_date_date_date_',date,it,'userId_,name>>',name,employeeindex)
            }
        } 
         
    }



}
let exportService=new ExportService();
export default exportService;